import { createWebHistory, createRouter } from 'vue-router'

import LoginView from '@/page/portal/Login.vue'
import HomeView from '@/page/portal/Home.vue'

const exclude = ['test'];

function getSubRoutes(): any[] {
  const pages = import.meta.glob('@/page/**/*.vue', { import: 'default', eager: true });

  const tree: any = {};
  Object.keys(pages).filter(key => {
    return !exclude.some(item => key.indexOf(`/src/page/${item}`) >= 0);
  }).forEach(key => {
    console.log(key);
    console.log(key.split("\/"))
    const pathSplist = key.split("\/");
    if (pathSplist.length > 4) {
      // /src/page/user/list/list.vue
      // /src/page/user/list/edit.vue
      // 将路径中的第3层作为路由跟节点
      let parentNodeName = pathSplist[3];
      let parentNode = tree[parentNodeName] || { name: parentNodeName, path: `/home/${parentNodeName}` };
      let importPath = pathSplist.slice(2, pathSplist.length).join("/");
      console.log("importPath: ", importPath);
      for (let i = 4; i < pathSplist.length; i++) {
        let nodeName = pathSplist[i]
        if (isDirectory(nodeName)) {
          continue;
        }

        let fileName = getFileName(nodeName);

        let routeNode = {
          path: `/home/${parentNodeName}/${fileName}`,
          component: pages[(key)],
          name: `${parentNodeName}-${fileName}`
        }
        parentNode.children = [routeNode].concat(parentNode.children || []);
      }
      tree[parentNodeName] = parentNode;
    }
  });

  let subRoutes: any[] = [];
  for (let key in tree) {
    console.log(key);
    subRoutes.push(tree[key]);
  }
  return subRoutes;
}

function isDirectory(path: string) {
  return path.indexOf(".vue") < 0;
}

function getFileName(file: string) {
  return file.split(".")[0];
}

const routes = [
  { path: '/', component: HomeView },
  { path: '/login', component: LoginView },
  {
    path: '/home',
    component: HomeView,
    children: getSubRoutes()
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router